package com.pigotech.ptwo.UI.Activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.pigotech.ptwo.R;
import com.pigotech.ptwo.RemoteCam;
import com.pigotech.ptwo.connect.IChannelListener;
import com.pigotech.ptwo.connect.IFragmentListener;
import com.pigotech.ptwo.socket.CommandSocket;
import com.pigotech.ptwo.widget.MediaController;
import com.pigotech.ptwo.widget.VideoView;

import org.json.JSONException;
import org.json.JSONObject;

import tv.danmaku.ijk.media.player.IjkMediaPlayer;


/**
 * 实时路况
 * Created by ghb on 2017/11/29.
 */

public class MonitorActivity extends BaseActivity implements View.OnClickListener,IChannelListener,IFragmentListener {
    private Button btn_start_session;
    private Button btn_start_play;
    private Button btn_stop_session;
    private Button btn_no_voice;
    private Button btn_start_record;
    private Button btn_take_photo;

    private VideoView mVideoView;
    private MediaController mMediaController;
    private String mVideoPath;//实时播放路径

    private RemoteCam mRemoteCam;

    private int mSessionId;
    private AlertDialog mAlertDialog;
    private ProgressDialog mProgressDialog;
    private boolean mIsPreview;
    private String mGetFileName;
    private String mPutFileName;
    private int mConnectivityType;
    private static final String TAG="MonitorActivity::";
    private static final int REQUEST_CODE_UPLOAD = 6384;
    private static final int REQUEST_CODE_WIFI_SETTINGS = 6385;

    final static String KEY_CONNECTIVITY_TYPE = "connectivity_type";
    final static String KEY_SELECTED_MODULE = "selected_module";
    final static String KEY_SELECTED_BT_DEVICE_NAME = "selected_bt_device_name";
    final static String KEY_SELECTED_BT_DEVICE_ADDR = "selected_bt_device_addr";

    public int statusBarHeight = -1;//系统状态栏高度
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_monitor);
        getStatusBarHeight();
        setStatusBar();
        initView();
        mVideoPath = "rtsp://192.168.42.1/live";
        livePlay();

//        WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        mRemoteCam = new RemoteCam(this);
//        mRemoteCam.setChannelListener(this)
//                .setBtDeviceAddr(mBTDeviceAddr)
//                .setConnectivity(mConnectivityType)
//                .setWifiInfo(wifiManager.getConnectionInfo().getSSID().replace("\"", ""),
//                        getWifiIpAddr());
//        mMediaFrag.setRemoteCam(mRemoteCam);
        mRemoteCam.setQuerySessionFlag(true);
    }

    /**
     * 获取系统状态栏高度
     */
    private void getStatusBarHeight() {
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
    }

    /**
     *4.4系统以上开启沉浸式后应用标题防止与系统标题重叠
     */
    private void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            findViewById(R.id.title_view).setVisibility(View.VISIBLE);
            findViewById(R.id.title_view).getLayoutParams().height = statusBarHeight;
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明底部导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    private void initView() {
        mVideoView = (VideoView) findViewById(R.id.video_view);
        btn_start_session = (Button) findViewById(R.id.btn_start_session);
        btn_start_play = (Button) findViewById(R.id.btn_start_play);
        btn_stop_session = (Button) findViewById(R.id.btn_stop_session);
        btn_no_voice = (Button) findViewById(R.id.btn_no_voice);
        btn_start_record = (Button) findViewById(R.id.btn_start_record);
        btn_take_photo = (Button) findViewById(R.id.btn_take_photo);

        btn_start_session.setOnClickListener(this);
        btn_start_play.setOnClickListener(this);
        btn_stop_session.setOnClickListener(this);
        btn_no_voice.setOnClickListener(this);
        btn_start_record.setOnClickListener(this);
        btn_take_photo.setOnClickListener(this);
    }


    /**
     * 调用此方法开启实时录制画面
     */
    public void livePlay() {
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
        mMediaController = new MediaController(this);

        mVideoView.setMediaController(mMediaController);
        mVideoView.setVideoPath(mVideoPath);
        mVideoView.requestFocus();
        mVideoView.start();
        mVideoView.setMediaController(null);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start_session:
                Log.d("GHB", "Click connect !");
                CommandSocket.getInstance().connect();
                break;
            case R.id.btn_start_play:
                Toast.makeText(this,"  ",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MonitorActivity.this, LiveViewWithAudio.class);
                intent.putExtra("videoPath", "rtsp://192.168.42.1/live");
                intent.putExtra("videoTitle", "Live");
                startActivity(intent);
                break;
            case R.id.btn_stop_session:
                Toast.makeText(this," dsfadsf ",Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_no_voice:
//                CommandSocket.getInstance().getNormalVideo();
                break;
            case R.id.btn_take_photo:
                Log.d("GHB", "Click take photo !");
                CommandSocket.getInstance().takePhoto();
                break;
        }
    }

    /**
     * IChannelListener
     */
    public void onChannelEvent(final int type, final Object param, final String...array) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (type & IChannelListener.MSG_MASK) {
                    case IChannelListener.CMD_CHANNEL_MSG:
                        handleCmdChannelEvent(type, param, array);
                        return;
                    case IChannelListener.DATA_CHANNEL_MSG:
                        handleDataChannelEvent(type, param);
                        return;
                    case IChannelListener.STREAM_CHANNEL_MSG:
                        handleStreamChannelEvent(type, param);
                        return;
                }
            }
        });
    }

    private void handleCmdChannelEvent(int type, Object param, String...array) {
        if (type >= 80) {
            handleCmdChannelError(type, param);
            return;
        }

        switch(type) {

            case IChannelListener.CMD_CHANNEL_EVENT_START_SESSION:
                mSessionId = (Integer)param;
                //mCommandsFrag.setSessionId(mSessionId);
                if (mSessionId > 0 ) {
                    Toast.makeText(getApplicationContext(), "< Session Start >", Toast.LENGTH_SHORT).show();
//                    mControlPanelFrag.setSessionStatus(true);
//                    FragmentTransaction ft = getFragmentManager().beginTransaction();
//                    ft.detach(mControlPanelFrag).attach(mControlPanelFrag).commit();
                } else {
                    Toast.makeText(getApplicationContext(), "< Session Start fail >", Toast.LENGTH_SHORT).show();
//                    mControlPanelFrag.setSessionStatus(false);
                }
//                mLogViewFrag.setSessionId(mSessionId);
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_STOP_SESSION:
                mSessionId = (Integer)param;
                if (mSessionId != 0) {
                    Toast.makeText(getApplicationContext(), "< !! SessionClose:FAIL !! >", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "< !! SessionClosed !! >", Toast.LENGTH_SHORT).show();
//                    mControlPanelFrag.setSessionStatus(false);
//                    FragmentTransaction ft = getFragmentManager().beginTransaction();
//                    ft.detach(mControlPanelFrag).attach(mControlPanelFrag).commit();
                    mSessionId = 0;
                }
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_SHOW_ALERT:
                showAlertDialog("Warning", (String)param);
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_LOG:
//                LogViewFragment.addLog((String) param);
//                if(saveLogToExternalStorage){
//                    String logString = param+"\r\n";
//                    try {
//                        external_logFile.write(((String) logString).getBytes());
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
                mRemoteCam.debugLastCmdResponse((String) param);
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_LS:
                dismissDialog();
//                mMediaFrag.updateDirContents((JSONObject) param);
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_SET_ATTRIBUTE:
                showAlertDialog("Info",
                        ((int)param != 0) ? "Set_Attribute failed" : "Set_Attribute OK");
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_FORMAT_SD:
//                mMediaFrag.showSD();
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_DEL:
//                mMediaFrag.refreshDirContents();
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_BATTERY_LEVEL:
            case IChannelListener.CMD_CHANNEL_EVENT_GET_INFO:
            case IChannelListener.CMD_CHANNEL_EVENT_GET_DEVINFO:
//                //getram
//                if (getFragmentManager().findFragmentById(R.id.fragment_placeholder) instanceof CommandsFragment)
//                    dismissDialog();
//                else
//                    showAlertDialog("Info", (String) param);
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_RESETVF:
                //getram
                // rest vf from CameraFragment
                ////mCameraFrag.onVFReset();
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_STOP_VF:
                //getram
                //do this only from CameraFragment
                ////mCameraFrag.onVFStopped();
                break;

            case IChannelListener.CMD_CHANNEL_EVENT_RECORD_TIME:
                ////mCameraFrag.upDateRecordTime((String)param);
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_SET_ZOOM:
//                mCameraFrag.setZoomDone((Integer)param);
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_QUERY_SESSION_HOLDER:
                mRemoteCam.actionQuerySessionHolder();
                break;

            case IChannelListener.CMD_CHANNEL_EVENT_GET_WIFI_SETTING:
//                mWifiSettingsFragment.updateWifiConfigOptions((String) param);
                break;

            case IChannelListener.CMD_CHANNEL_EVENT_GET_ZOOM_INFO:
//                mCameraFrag.setZoomInfo((String)param, array[0]);
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_GET_ALL_SETTINGS:
                JSONObject parser = (JSONObject)param;
                try {
                    if (parser.getInt("rval") < 0)
                        showAlertDialog("Warning", "Setting is not support by remote camera !");
                    else {
//                        if (getFragmentManager().findFragmentById(R.id.fragment_placeholder) instanceof CommandsFragment)
//                            dismissDialog();
//                        else
//                            mSettingsFrag.updateAllSettings(parser);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_GET_OPTIONS:
//                mSettingsFrag.updateSettingOptions((JSONObject)param);
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_SET_SETTING:
//                mSettingsFrag.updateSettingNotification((JSONObject)param);
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_START_CONNECT:
                showWaitDialog("Connecting to Remote Camera");
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_START_LS:
                showWaitDialog("Fetching Directory Info");
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_WAKEUP_START:
                showWaitDialog("Waking up the Remote Camera");
                break;
            case IChannelListener.CMD_CHANNEL_EVENT_CONNECTED:
            case IChannelListener.CMD_CHANNEL_EVENT_WAKEUP_OK:
                dismissDialog();
                break;

        }
    }

    private void handleDataChannelEvent(int type, Object param) {
        switch(type) {
            case IChannelListener.DATA_CHANNEL_EVENT_GET_START:
                String str = mIsPreview ? "Please wait ..." : "Downloading ,,,";
                showProgressDialog(str,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface Dialog, int which) {
                                mRemoteCam.cancelGetFile(mGetFileName);
                            }
                        });
                break;
            case IChannelListener.DATA_CHANNEL_EVENT_GET_PROGRESS:
                mProgressDialog.setProgress((Integer) param);
                break;
            case IChannelListener.DATA_CHANNEL_EVENT_GET_FINISH:
                String path = (String)param;
                if (!mIsPreview) {
                    showAlertDialog("Info", "Downloaded to " + path);
                    mGetFileName = null;
                } else {
                    dismissDialog();
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse("file://" + path), "image/*");
                    startActivity(intent);
                    mIsPreview = false;
                }
                break;

            case IChannelListener.DATA_CHANNEL_EVENT_PUT_MD5:
                showWaitDialog("Calculating MD5");
                break;
            case IChannelListener.DATA_CHANNEL_EVENT_PUT_START:
                showProgressDialog("Uploading...",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface Dialog, int which) {
                                mRemoteCam.cancelPutFile(mPutFileName);
                            }
                        });
                break;
            case IChannelListener.DATA_CHANNEL_EVENT_PUT_PROGRESS:
                mProgressDialog.setProgress((Integer) param);
                break;
            case IChannelListener.DATA_CHANNEL_EVENT_PUT_FINISH:
                showAlertDialog("Info", "Uploaded to " + mPutFileName);
                mPutFileName = null;
//                mMediaFrag.refreshDirContents();
                break;
        }
    }
    private void handleStreamChannelEvent(int type, Object param) {
        switch(type) {
            case IChannelListener.STREAM_CHANNEL_EVENT_BUFFERING:
                showWaitDialog("Buffering...");
                break;
            case IChannelListener.STREAM_CHANNEL_EVENT_PLAYING:
                dismissDialog();
//                mCameraFrag.startStreamView();
                break;
            case IChannelListener.STREAM_CHANNEL_ERROR_PLAYING:
                mRemoteCam.stopLiveStream();
//                mCameraFrag.resetStreamView();
                showAlertDialog("Error", "Cannot connect to LiveView!");
                break;
        }
    }
    private void handleCmdChannelError(int type, Object param) {
        switch (type) {
            case IChannelListener.CMD_CHANNEL_ERROR_INVALID_TOKEN:
                showAlertDialog("Error", "Invalid Session! Please start session first!");
                break;
            case IChannelListener.CMD_CHANNEL_ERROR_TIMEOUT:
                showAlertDialog("Error", "Timeout! No response from Remote Camera!");
                break;
            case IChannelListener.CMD_CHANNEL_ERROR_BLE_INVALID_ADDR:
                showAlertDialog("Error", "Invalid bluetooth device");
                break;
            case IChannelListener.CMD_CHANNEL_ERROR_BLE_DISABLED:
                startBluetoothSettings();
                break;
            case IChannelListener.CMD_CHANNEL_ERROR_BROKEN_CHANNEL:
                showAlertDialog("Error", "Lost connection with Remote Camera!");
                resetRemoteCamera();
                break;
            case IChannelListener.CMD_CHANNEL_ERROR_CONNECT:
                showAlertDialog("Error",
                        "Cannot connect to the Camera. \n" +
                                "Please make sure the selected camera is on. \n" +
                                "If problem persists, please reboot both camera and this device.");
                break;
            case IChannelListener.CMD_CHANNEL_ERROR_WAKEUP:
                showAlertDialog("Error", "Cannot wakeup the Remote Camera");
                break;
        }
    }

    @Override
    public void onFragmentAction(int type, Object param, Integer... array) {
        Intent intent;
        switch (type) {

            case IFragmentListener.ACTION_CONNECTIVITY_SELECTED:
                mConnectivityType = (Integer)param;
                resetRemoteCamera();
                mRemoteCam.setConnectivity(mConnectivityType);
                break;
            case IFragmentListener.ACTION_WIFI_LIST:
                intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                startActivityForResult(intent, REQUEST_CODE_WIFI_SETTINGS);
                break;
            case IFragmentListener.ACTION_SET_CAMERA_WIFI_IP:  //Getram
                mRemoteCam.setWifiIP((String) param, 7878, 8787);
                break;
            case IFragmentListener.ACTION_OPEN_CONTROLPANEL:
//                mControlPanelFrag.setClientBtAddr(getLocalBTHWAddress());
//                openControlPanel();
                break;
            case IFragmentListener.ACTION_BC_START_SESSION:
                SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
                mRemoteCam.ble_connection_timeout = Integer.parseInt(mySharedPreferences.getString("ble_connection_retry_timeout","10"));
                mRemoteCam.gatt_autoConnect_flag = mySharedPreferences.getBoolean("ble_gatt_auto_reconnect_checkbox",false);
                mRemoteCam.startSession();
                break;
            case IFragmentListener.ACTION_BC_STOP_SESSION:
                mRemoteCam.stopSession();
                break;
            case IFragmentListener.ACTION_BC_SEND_COMMAND:
                mRemoteCam.sendCommand((String) param);
                break;
            case IFragmentListener.ACTION_SET_QUERY_SESSION_HOLDER:
                mRemoteCam.setQuerySessionFlag(true);
                break;
            case IFragmentListener.ACTION_UNSET_QUERY_SESSION_HOLDER:
                mRemoteCam.setQuerySessionFlag(false);
                break;
            case IFragmentListener.ACTION_OPEN_CAMERA_COMMANDS:
//                openCommandsFragment();
                break;
            case IFragmentListener.ACTION_OPEN_CAMERA_LIVEVIEW:
//                openCameraFragment();
                break;
            case IFragmentListener.ACTION_OPEN_CAMERA_FILE_CMDS:
//                openMediaFragment();
                break;
            case IFragmentListener.ACTION_OPEN_CAMERA_SETTINGS:
//                openSettingsFragment();
                break;
            case IFragmentListener.ACTION_OPEN_CAMERA_WIFI_SETTINGS:
//                openWifiSettingsFragment();
                break;
            case IFragmentListener.ACTION_OPEN_LOG_VIEW:
//                openLogView();
                break;
            case IFragmentListener.ACTION_BC_SET_CLIENT_INFO:
                mRemoteCam.setClientInfo();
                break;
            case IFragmentListener.ACTION_DISC_SPACE:
                mRemoteCam.getTotalDiskSpace();
                break;
            case IFragmentListener.ACTION_DISC_FREE_SPACE:
                mRemoteCam.getTotalFreeSpace();
                break;
            case IFragmentListener.ACTION_APP_STATUS:
                mRemoteCam.appStatus();
                break;
            case IFragmentListener.ACTION_DEVICE_INFO:
                mRemoteCam.getDeviceInfo();
                break;
            case IFragmentListener.ACTION_BATTERY_INFO:
                mRemoteCam.getBatteryLevel();
                break;
            case IFragmentListener.ACTION_BC_GET_CURRENT_SETTING:
                mRemoteCam.getAllSettings();
                break;
            case IFragmentListener.ACTION_BC_GET_ALL_SETTINGS:
                showWaitDialog("Fetching Settings Info");
                mRemoteCam.getAllSettings();
                break;
            case IFragmentListener.ACTION_BC_GET_ALL_SETTINGS_DONE:
                dismissDialog();
                break;
            case IFragmentListener.ACTION_BC_GET_SETTING_OPTIONS:
                mRemoteCam.getSettingOptions((String) param);
                break;
            case IFragmentListener.ACTION_BC_SET_SETTING:
                mRemoteCam.setSetting((String) param);
                break;
            case IFragmentListener.ACTION_BC_SET_BITRATE:
                mRemoteCam.setBitRate((Integer) param);
                break;
            case IFragmentListener.ACTION_PHOTO_START:
                mRemoteCam.takePhoto();
                break;
            case IFragmentListener.ACTION_PHOTO_STOP:
                mRemoteCam.stopPhoto();
            case IFragmentListener.ACTION_RECORD_START:
                mRemoteCam.startRecord();
//                mCameraFrag.startRecord();
                break;
            case IFragmentListener.ACTION_RECORD_STOP:
                mRemoteCam.stopRecord();
//                mCameraFrag.stopRecord();
                break;
            case IFragmentListener.ACTION_RECORD_TIME:
                mRemoteCam.getRecordTime();
                break;
            case IFragmentListener.ACTION_FORCE_SPLIT:
                mRemoteCam.forceSplit();
                break;
            case IFragmentListener.ACTION_VF_START:
                mRemoteCam.startVF();
                break;
            case IFragmentListener.ACTION_VF_STOP:
                mRemoteCam.stopVF();
                break;
            case IFragmentListener.ACTION_PLAYER_START:
                mRemoteCam.startLiveStream();
                break;
            case IFragmentListener.ACTION_PLAYER_STOP:
                mRemoteCam.stopLiveStream();
//                mCameraFrag.stopStreamView();
                break;
            case IFragmentListener.ACTION_FS_GET_FILE_INFO:
                mRemoteCam.getMediaInfo();
                break;
            case IFragmentListener.ACTION_FS_GET_ALL_FILE_COUNT:
                mRemoteCam.getTotalFileCount();
                break;
            case IFragmentListener.ACTION_FS_GET_ALL_VIDEO_FILES:
                mRemoteCam.getAllVideoFilesCount();
                break;
            case IFragmentListener.ACTION_FS_GET_ALL_PHOTO_FILES:
                mRemoteCam.getAllPhotoFilesCount();
                break;
            case IFragmentListener.ACTION_FS_FORMAT_SD:

//                mFormatSdParam = (String)param;
                new AlertDialog.Builder(this)
                        .setTitle("Warning")
                        .setMessage("Are you sure to format SD card?")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                                mRemoteCam.formatSD((String)mFormatSdParam);
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .show();
                break;
            case IFragmentListener.ACTION_FS_GET_PWD:
                mRemoteCam.getPWD();
                break;
            case IFragmentListener.ACTION_FS_LS:
                mRemoteCam.listDir((String) param);
                break;
            case IFragmentListener.ACTION_FS_CD:
                mRemoteCam.changeFolder((String) param);
                break;
            case IFragmentListener.ACTION_FS_DELETE:
                mRemoteCam.deleteFile((String)param);
                break;
            case IFragmentListener.ACTION_FS_DOWNLOAD:
                mGetFileName = (String)param;
                mRemoteCam.getFile(mGetFileName);
                break;
            case IFragmentListener.ACTION_FS_INFO:
                mRemoteCam.getInfo((String)param);
                break;
            case IFragmentListener.ACTION_FS_SET_RO:
                mRemoteCam.setMediaAttribute((String)param, 0);
                break;
            case IFragmentListener.ACTION_FS_SET_WR:
                mRemoteCam.setMediaAttribute((String)param, 1);
                break;
            case IFragmentListener.ACTION_FS_GET_THUMB:
                mRemoteCam.getThumb((String)param);
                break;
            /*case IFragmentListener.ACTION_FS_BURN_FW:
                mRemoteCam.burnInFw((String) param);
                break;*/
            case IFragmentListener.ACTION_FS_VIEW:
                String path = (String) param;
                if (path.endsWith(".jpg")) {
                    mIsPreview = true;
                    mRemoteCam.getFile(path);
                } else {
                    String uri = mRemoteCam.streamFile(path);
                    intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse(uri), "video/mp4");
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                        new AlertDialog.Builder(this)
                                .setTitle("Warning")
                                .setMessage("You don't have any compatible video player installed in your device. " +
                                        "Please install one (such as RTSP player) first.")
                                .setPositiveButton("OK", null)
                                .show();
                    }
                }
                break;

            case IFragmentListener.ACTION_GET_ZOOM_INFO:
                mRemoteCam.getZoomInfo((String)param);
                break;
            case IFragmentListener.ACTION_SET_ZOOM:
                mRemoteCam.setZoom((String)param, array[0]);
                break;

            case IFragmentListener.ACTION_BT_LIST:
               /* getFragmentManager().beginTransaction()
                        .replace(R.id.fragment_placeholder, new BTSelectFragment())
                        .commit();
                break;*/
                break;
            case IFragmentListener.ACTION_BLE_LIST:
//                getFragmentManager().beginTransaction()
//                        .replace(R.id.fragment_placeholder, new BLESelectFragment())
//                        .commit();
                break;

            case IFragmentListener.ACTION_BT_SELECTED:
                String device[] = (String[]) param;
//                if (!mBTDeviceAddr.equals(device[1])) {
//                    mBTDeviceName = device[0];
//                    mBTDeviceAddr = device[1];
//                    resetRemoteCamera();
//                    mRemoteCam.setBtDeviceAddr(mBTDeviceAddr);
//                }
            case IFragmentListener.ACTION_BT_CANCEL:
//                presentBLEWifiSetupFragment();
                break;
            case IFragmentListener.ACTION_BT_ENABLE:
//                startBluetoothSettings();
                break;
            case IFragmentListener.ACTION_SHOW_LAST_CMD_RESP:
                String debgString;
                debgString = mRemoteCam.lastCommandResponse;
                debgString = debgString.replaceAll("<font color=#cc0029>", "[");
                debgString = debgString.replaceAll("<br ></font>", "]");
                Toast.makeText(getApplicationContext(), debgString , Toast.LENGTH_SHORT).show();
                break;

            case IFragmentListener.ACTION_GET_WIFI_SETTINGS:
                mRemoteCam.getWifiSettings();
                break;
            case IFragmentListener.ACTION_SET_WIFI_SETTINGS:
                mRemoteCam.setWifiSettings((String) param);
                break;
            case IFragmentListener.ACTION_WIFI_STOP:
                mRemoteCam.stopWifi();
                break;
            case IFragmentListener.ACTION_WIFI_START:
                mRemoteCam.startWifi();
                break;
            case IFragmentListener.ACTION_WIFI_RESTART:
                mRemoteCam.restartWifi();
                break;
            case IFragmentListener.ACTION_CLOSE_BLE:
                mRemoteCam.closeBLEConnection();
                break;
            case IFragmentListener.ACTION_FS_BURN_FW:
                mRemoteCam.burnFW((String) param);
                break;
            case IFragmentListener.ACTION_CLOSE_EXTERNAL_LOG_FILE:
//                if(saveLogToExternalStorage){
//                    try {
//                        external_logFile.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }

        }
    }

    private void startBluetoothSettings() {
        dismissDialog();
        mAlertDialog = new AlertDialog.Builder(this)
                .setTitle("Alert")
                .setMessage("Bluetooth is disabled currently. \nPlease turn it on first.")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final Intent  intent = new
                                Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
                        startActivity(intent);
                    }
                })
                .show();
    }

    // Misc Operations
    /**
     * reset RemoteCam due to:
     *     1. Lost of connections.
     *     2. Use selected a different camera
     */
    private void resetRemoteCamera() {
        mRemoteCam.reset();
//        mCameraFrag.reset();
//        mMediaFrag.reset();
//        mLogViewFrag.reset();
//        mCameraCommandsFrag.reset();
//        mSettingsFrag.reset();
//        mWifiSettingsFragment.reset();
    }

    private void showAlertDialog(String title, String msg) {
        dismissDialog();
        mAlertDialog = new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(msg)
                .setPositiveButton("OK", null)
                .show();
    }

    private void dismissDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
        if (mAlertDialog != null) {
            mAlertDialog.dismiss();
        }
    }
    private void showWaitDialog(String msg) {
        dismissDialog();
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("PLEASE WAIT ...");
        mProgressDialog.setMessage(msg);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

    private void showProgressDialog(String title,
                                    DialogInterface.OnClickListener listener) {
        dismissDialog();
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle(title);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                "Cancel", listener);
        mProgressDialog.show();
    }
}
